package com.ken.blog.service.impl;

import com.ken.blog.domain.Category;
import com.ken.blog.domain.CategoryRepository;
import com.ken.blog.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    public static final String CACHE_KEY = "list";

    @Autowired
    CategoryRepository categoryRepository;

    @Override
    @Transactional(rollbackFor = {IllegalArgumentException.class})
    public Category saveCategory(Category category) {
        Category result = categoryRepository.save(category);
        //测试分类仅能添加一次
        if (result.getTitle().equals("测试")) {
            throw new IllegalArgumentException("测试已经存在，数据已经回滚");
        }
        return result;
    }

    @Override
    @CachePut(value = "category", key = "#root.target.CACHE_KEY")
    public List<Category> getCategoryList() {
        List<Category> categoryList = categoryRepository.findAll();
        System.out.println("存储了分类缓存");
        return categoryList;
    }
}
